//
//  ZCommonUtils.m
//  DLNavigationTabBar
//
//  Created by xunshian on 17/1/23.
//  Copyright © 2017年 FT_David. All rights reserved.
//

#import "ZCommonUtils.h"
//#import "AFNetworkReachabilityManager.h"

#import <sys/sysctl.h>
#define IOS7   [[UIDevice currentDevice]systemVersion].floatValue>=7.0


#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>


#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>

@implementation ZCommonUtils
#pragma mark -********************
#pragma mark -CommonUtils
#pragma mark -********************
/**
 *  注意监测是否有网的该方法在一个页面中最好只用一次
 //检查网络是否－－畅通的方法(该方法在同一个类里面同一时间只会执行最后的那一次调用)
 */
//-(void)checkNet
//{
//    NSLog(@"检测网络");
//    AFNetworkReachabilityManager* manager = [AFNetworkReachabilityManager sharedManager];
//    //开始检测网络
//    [manager startMonitoring];
//    NSLog(@"有网：%d",[manager isReachable]);
//    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        //status存放当前的网络状态
//        switch (status) {
//            case AFNetworkReachabilityStatusReachableViaWiFi:
//                //wifi
//                self.block(1);
//                break;
//                
//            case AFNetworkReachabilityStatusReachableViaWWAN:
//                //4G网
//                self.block(2);
//                break;
//                
//            case AFNetworkReachabilityStatusNotReachable:
//                //未连接
//                self.block(0);
//                break;
//                
//            case AFNetworkReachabilityStatusUnknown:
//                //未知网络
//                self.block(3);
//                break;
//            default:
//                break;
//        }
//    }];
//}
+(BOOL)isFirstBundleVersion
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    if ([defaults objectForKey:@"Version"])
    {
        //通过系统的取版本号
        NSString *systemVersion = [[NSBundle mainBundle]objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
        //是否是第一次进入这个版本
        BOOL isFirstVersion = [systemVersion isEqualToString:[defaults objectForKey:@"Version"]];
        //不论是否当前版本都将版本号存入新值
        [defaults setObject:systemVersion forKey:@"Version"];
        [defaults synchronize];
        //比较存入的版本号是否相同，如果同，进入tabBar页面，否则进入滚动页面
        if (isFirstVersion)
        {
            return NO;
            
        }else
        {
            return YES;
        }
        
        
    }
    NSString *systemVersion = [[NSBundle mainBundle]objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
    [defaults setObject:systemVersion forKey:@"Version"];
    [defaults synchronize];
    
    return YES;
}

//自定义的1.white 2.black
//更改状态栏颜色
+(void)changeStatusBarWhite
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"1" forKey:@"statusBarColor"];
    [defaults synchronize];
}
+(void)changeStatusBarBlack
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"0" forKey:@"statusBarColor"];
    [defaults synchronize];
    
}
+(CGSize)contentSize:(UILabel *)label
{
    //NSLog(@"%@",label.text);
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    //    paragraphStyle.lineBreakMode =  label.lineBreakMode;
    paragraphStyle.alignment = label.textAlignment;
    NSDictionary *attributes = @{NSFontAttributeName:label.font, NSParagraphStyleAttributeName:paragraphStyle};
    CGSize contentSize = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return contentSize;
}

+(CGSize)contentSizeWithStr:(NSString *)str andFont:(UIFont *)font andWidth:(CGFloat)labelWidth
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode =  NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle};
    CGSize contentSize = [str boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return contentSize;
}

+(CGSize)contentSizeAll:(UILabel *)label andLineSpacingHeight:(NSInteger) lineSpacingHeight
{
    
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:label.text];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [paragraphStyle setLineSpacing:lineSpacingHeight];//调整行间距////行自定义行高度
    
    label.numberOfLines = 0;
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];
    // [atrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:32] range:range];
    paragraphStyle.alignment = label.textAlignment;
    NSDictionary *attributes = @{NSFontAttributeName:label.font, NSParagraphStyleAttributeName:paragraphStyle};
    
    CGSize contentSize = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    
    return contentSize;
}

+(UILabel *)createAttributeLabel:(UILabel *)label andLineSpacingHeight:(NSInteger) lineSpacingHeight{
    
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:label.text];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    // paragraphStyle.lineBreakMode =  label.lineBreakMode;
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    [paragraphStyle setLineSpacing:lineSpacingHeight];//调整行间距//行自定义行高度
    //paragraphStyle.maximumLineHeight = 60;  //最大的行高
    //段落与段落之间的竖向距离
    //[paragraphStyle setParagraphSpacing:40];
    
    //段首行缩进
    //[paragraphStyle setFirstLineHeadIndent:4];
    //段尾行缩进 // Distance from margin to front edge of paragraph
    //[paragraphStyle setHeadIndent:40];
    
    //[paragraphStyle setTailIndent:20];
    
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];
     //[atrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:32] range:range];
    
    label.attributedText = attributeString;
    return label;
}
//返回字符串的高度
+ (CGFloat)textHeightWithString:(NSString *)text width:(CGFloat)width fontSize:(NSInteger)fontSize
{
    NSDictionary *dict = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
    // 根据第一个参数的文本内容，使用280*float最大值的大小，使用系统14号字，返回一个真实的frame size : (280*xxx)!!
    CGRect frame = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    return frame.size.height + 5;
}


#pragma mark -********************
#pragma mark -UIColor+tools.h
#pragma mark -********************
/// 十六进制转换 + 不透明
+ (UIColor *)colorWithHexString:(NSString *)hexString
{
    return [self colorWithHexString:hexString alpha:1.0f];
}

/// 十六进制转换 + 透明度
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha
{
    unsigned int red, green, blue;
    NSRange range;
    range.length =2;
    
    range.location =0;
    [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&red];
    range.location =2;
    [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&green];
    range.location =4;
    [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red/255.0f)green:(float)(green/255.0f)blue:(float)(blue/255.0f)alpha:alpha];
}

#pragma mark -********************
#pragma mark -UIImage+tools.h
#pragma mark -********************
+ (UIImage *)loadPngImageWithName:(NSString *)name
{
    return [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:@"png"]];
}

+ (UIImage *)loadJpgImageWithName:(NSString *)name
{
    return [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:@"jpg"]];
}

+ (UIImage *) createImageWithColor: (UIColor *) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}


#pragma mark -********************
#pragma mark -UIZZJ.h
#pragma mark -********************
//1.设置控件的位置和大小 2.设置控件的用户交互 3.设置相应控件的常用属性－－其他的采用默认的
+(UILabel*)createLabelWithFrame:(CGRect)frame font:(int)font text:(NSString*)text
{
    UILabel*label=[[UILabel alloc]initWithFrame:frame];
    //限制行数
    label.numberOfLines=0;
    //对齐方式
    label.textAlignment=NSTextAlignmentLeft;
    label.backgroundColor=[UIColor clearColor];
    label.font=[UIFont systemFontOfSize:font];
    //单词折行
    label.lineBreakMode=NSLineBreakByWordWrapping;
    //默认字体颜色是白色
    label.textColor=[UIColor blackColor];
    //自适应（行数~字体大小按照设置大小进行设置）
    label.adjustsFontSizeToFitWidth=YES;
    label.text=text;
    return label;
}
+(UILabel *)createLabel:(CGRect)cgRect font:(UIFont *)font textColor:(UIColor*)textColor text:(NSString *)text backGroundColor:(UIColor *)bgColor textAlignment:(NSInteger)alignmentType
{
    UILabel *label = [[UILabel alloc]initWithFrame:cgRect];
    //nil默认－－－颜色需特殊处理
    if (bgColor)
    {
        label.backgroundColor = bgColor;
    }
    label.userInteractionEnabled = YES;
    label.textAlignment = alignmentType;
    label.font = font;
    label.textColor = textColor;
    label.text = text;
    return label;
}

+(UIImageView *)createImageView:(CGRect)cgRect imageName:(NSString *)imageName
{
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:cgRect];
    imgV.userInteractionEnabled = YES;
    imgV.image = [UIImage imageNamed:imageName];
    return imgV;
}

+(UIButton*)createBtnWithFrame:(CGRect)frame target:(id)target action:(SEL)action title:(NSString*)title imageName:(NSString*)imageName bgImageName:(NSString *)bgImageName
{
    UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=frame;
    [button setTitle:title forState:UIControlStateNormal];
//    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    button.titleLabel.font = [UIFont systemFontOfSize:14];
    //图片与文字如果需要同时存在，就需要图片足够小 详见人人项目按钮设置
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    //设置背景图片，可以使文字与图片共存
    [button setBackgroundImage:[UIImage imageNamed:bgImageName] forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

+(UIButton *)createBtn:(CGRect)cgRect target:(id)target sel:(SEL)sel title:(NSString *)title titleColor:(UIColor *)titleColor font:(UIFont *)font image:(NSString *)imageName backGroundImage:(NSString *)backImage
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = cgRect;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
    btn.titleLabel.font = font;
    [btn addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

+(UIButton *)createBtn:(CGRect)cgRect target:(id)target sel:(SEL)sel title:(NSString *)title titleColor:(UIColor *)titleColor font:(UIFont *)font image:(NSString *)imageName backGroundImage:(NSString *)backImage  ContentHorizontalAlignment:(UIControlContentHorizontalAlignment)contentHorizontalAlignment ContentEdgeInsets:(UIEdgeInsets)uIEdgeInsets TitleEdgeInsets:(UIEdgeInsets)titleEdgeInsets ImagecontentMode:(UIViewContentMode)imagecontentMode{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = cgRect;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
    btn.titleLabel.font = font;
    [btn addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    
    //设置内容的显示
    btn.contentHorizontalAlignment = contentHorizontalAlignment;
    //btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //设置内容的偏移量
    //btn.contentEdgeInsets = UIEdgeInsetsMake(5, 0, 0, 0);
    btn.contentEdgeInsets = uIEdgeInsets;
    //设置标题的偏移量
    //btn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    btn.titleEdgeInsets = titleEdgeInsets;
    //设置bgBtn的图片视图的内容模式
    //btn.imageView.contentMode = UIViewContentModeCenter;
    btn.imageView.contentMode = imagecontentMode;
    
    return btn;
}

//自定义 Button
- (UIButton *)createBtnWithCustomType:(UIButtonType)buttonType target:(id)target selector:(SEL)selcector title:(NSString *)title titleColor:(UIColor *)titleColor titleFont:(UIFont *)font image:(NSString *)imageName highLightedImage:(NSString *)highLightImageName  bgImage:(NSString *)bGimageName hightLightedBGImage:(NSString *)highLightedBGImageName{
    //1、添加背景的btn
    UIButton *bgBtn = [UIButton buttonWithType:buttonType];
    [bgBtn setTitle:title forState:UIControlStateNormal];
    //设置字体颜色
    [bgBtn setTitleColor:titleColor forState:UIControlStateNormal];
    //设置字体大小
    bgBtn.titleLabel.font = font;
    //添加事件监听
    [bgBtn addTarget:target action:selcector forControlEvents:UIControlEventTouchUpInside];
    //设置图片
    [bgBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [bgBtn setImage:[UIImage imageNamed:highLightImageName] forState:UIControlStateHighlighted];
    
    //对bgBtn添加背景
    UIImage *image = [[UIImage imageNamed:bGimageName] resizableImageWithCapInsets:UIEdgeInsetsMake(44, 0, 44, 1) resizingMode:UIImageResizingModeStretch];
    UIImage *highLightedImage = [[UIImage imageNamed:highLightedBGImageName] resizableImageWithCapInsets:UIEdgeInsetsMake(44, 0, 44, 1) resizingMode:UIImageResizingModeStretch];
    //上面只是设置图片拉伸方式而已。无影响 -z
    //        UIImage *image = [UIImage imageNamed:@"buddy_header_bg"];
    //        UIImage *highLightedImage = [UIImage imageNamed:@"buddy_header_bg_highlighted"];
    [bgBtn setBackgroundImage:image forState:UIControlStateNormal];
    [bgBtn setBackgroundImage:highLightedImage forState:UIControlStateHighlighted];
//    //设置内容的显示
//    bgBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;//设置文字位置，现设为居左，默认的是居中
//    //设置内容的偏移量 上 左 下 右
//    bgBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);//使文字距离做边框保持10个像素的距离。
//    //设置标题的偏移量
//    bgBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
//    //设置bgBtn的图片视图的内容模式
//    bgBtn.imageView.contentMode = UIViewContentModeCenter;
//    bgBtn.imageView.clipsToBounds = NO;
    return bgBtn;
}

#pragma mark -创建scView
+(UIScrollView *)createScView:(CGRect)cgRect target:(id)target sizeWidth:(CGFloat)width sizeHeight:(CGFloat)height offsetX:(CGFloat)X offsetY:(CGFloat)Y horizontalIndicator:(BOOL)horizon verticalIndicator:(BOOL)vertical bounces:(BOOL)bounces pageEnable:(BOOL)pageEnable
{
    //可以封装一下
    UIScrollView *scView = [[UIScrollView alloc]initWithFrame:cgRect];
    scView.contentSize = CGSizeMake(width, height);
    scView.contentOffset = CGPointMake(X,Y);
    //水平滑动条
    scView.showsHorizontalScrollIndicator = horizon;
    //垂直滑动条
    scView.showsVerticalScrollIndicator = vertical;
    //弹性
    scView.bounces = bounces;
    //翻一页
    scView.pagingEnabled = pageEnable;
    return scView;
}

#pragma mark -创建tableView 默认是grouped的  可以通过typeNameDefaultGrouped 设置plain 值为字符串@"plain"
+(UITableView *)createTableView:(CGRect)cgRect dataSourceTarget:(id)target1 delegateTarget:(id)target2 horizontalIndicator:(BOOL)horizon verticalIndicator:(BOOL)vertical type:(NSString*)typeNameDefaultGrouped separatorStyle:(UITableViewCellSeparatorStyle)style
{
    UITableView *tableView;
    if([typeNameDefaultGrouped isEqualToString:@"plain"])
    {
        tableView = [[UITableView alloc]initWithFrame:cgRect style:UITableViewStylePlain];
    }else
    {
        tableView = [[UITableView alloc]initWithFrame:cgRect style:UITableViewStyleGrouped];
    }
    tableView.delegate = target1;
    tableView.dataSource = target2;
    tableView.showsHorizontalScrollIndicator =horizon;
    tableView.showsVerticalScrollIndicator = vertical;
    tableView.separatorStyle = style;
    return tableView;
}

+ (UITableView *)createTableViewWithFrame:(CGRect)frame tableViewStyle:(UITableViewStyle)tableViewStyle dataSource:(id<UITableViewDataSource>) dataSource deleaget:(id<UITableViewDelegate>) delegate bgColor:(UIColor *)bgColor tableHeaderView:(UIView *)tableHeaderView tableFooterView:(UIView *)tableFooterView  separatorStyle:(UITableViewCellSeparatorStyle )separatorStyle separatorColor:(UIColor *)separatorColor userInteractionEnabled:(BOOL) userInteractionEnabled scrollEnabled:(BOOL)scrollEnabled horizontalIndicator:(BOOL)horizon verticalIndicator:(BOOL)vertical{
    
    // tableView有两种样式
    //     UITableViewStylePlain  普通的表格样式 组头是有粘性的 表现为cell滚动在当前组时组头会一直显示在最上方
    //    UITableViewStyleGrouped  分组模式 组头是没有粘性的 表现为组头会一直随cell滚动
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:tableViewStyle];
    //tableView 设置代理
    tableView.dataSource = dataSource;
    tableView.delegate = delegate;
    tableView.userInteractionEnabled = userInteractionEnabled;//控制tableView的是否打开用户交互 默认是YES
    tableView.scrollEnabled = scrollEnabled;//控制tableView是否可以滑动 默认是YES
    tableView.showsHorizontalScrollIndicator =horizon;
    tableView.showsVerticalScrollIndicator = vertical;
    //1.tableView本身相关的
    
    tableView.backgroundColor = bgColor;
    //设置整个tablView的头部/尾部视图
    tableView.tableHeaderView = tableHeaderView;
    tableView.tableFooterView = tableFooterView;
    //设置分割线样式
    tableView.separatorStyle = separatorStyle;// UITableViewCellSeparatorStyleNone,  没有分隔线
    // UITableViewCellSeparatorStyleSingleLine, 正常分隔线
    //设置我们分割线颜色(clearColor相当于取消系统分割线)
    tableView.separatorColor = separatorColor;//[UIColor clearColor]
    
    //2.tableView的section相关
    
    //组头组尾的高
    //    tableView.sectionHeaderHeight = kSectionHeaderHeight;
    //    tableView.sectionFooterHeight = kSectionFooterHeight;
    //    /* 估算的统一的每一组头部高度，设置估算高度可以优化性能 */
    //    tableView.estimatedSectionHeaderHeight = kSectionHeaderHeight;
    //    /* 估算的统一的每一组的尾部高度 */
    //    tableView.estimatedSectionFooterHeight = kSectionFooterHeight;
    
    
    //2.tableView的cell相关的
    
    //    // 告诉tableView的真实高度是自动计算的，根据你的约束来计算
    //    tableView.rowHeight = UITableViewAutomaticDimension;
    //    //修改tableView的行高
    //    //tableView.rowHeight = 100;
    //    // 告诉tableView所有cell的估计行高
    //    tableView.estimatedRowHeight = kCellHeight;
    //    // 返回估算告诉,作用:在tablView显示时候,先根据估算高度得到整个tablView高,而不必知道每个cell的高度,从而达到高度方法的懒加载调用
    
    //3.tableView的索引相关 sectionIndex
    
    //    // 设置索引条内部文字颜色
    //    tableView.sectionIndexColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
    //    // 设置索引条背景颜色
    //    tableView.sectionIndexBackgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
    
    //5.tableView的编辑模式 editing
    
    //    tableView.editing = YES;/* 是否是编辑模式，默认是NO */
    //    tableView.allowsSelection = YES;/* tableView处在非编辑模式的时候是否允许选中行，默认是YES */
    //    tableView.allowsSelectionDuringEditing = NO;/* tableView处在编辑模式的时候是否允许选中行，默认是NO */
    //    tableView.allowsMultipleSelection = NO;/* tableView处在非编辑模式的时候是否允许选中多行数据，默认是NO */
    //    tableView.allowsSelectionDuringEditing = NO;/* tableView处在编辑模式的时候是否允许选中多行数据，默认是NO */
    
    return tableView;
}


+(UIView*)createViewWithFrame:(CGRect)frame
{
    UIView*view=[[UIView alloc]initWithFrame:frame];
    
    return view ;
    
}
+(UITextField*)createTextFieldWithFrame:(CGRect)frame placeholder:(NSString*)placeholder passWord:(BOOL)YESorNO leftImageView:(UIImageView*)imageView rightImageView:(UIImageView*)rightImageView Font:(float)font
{
    UITextField*textField=[[UITextField alloc]initWithFrame:frame];
    //灰色提示框
    textField.placeholder=placeholder;
    //文字对齐方式
    textField.textAlignment=NSTextAlignmentLeft;
    textField.secureTextEntry=YESorNO;
    //边框
    //textField.borderStyle=UITextBorderStyleLine;
    //键盘类型
    textField.keyboardType=UIKeyboardTypeEmailAddress;
    //关闭首字母大写
    textField.autocapitalizationType=NO;
    //清除按钮
    textField.clearButtonMode=YES;
    //左图片
    textField.leftView=imageView;
    textField.leftViewMode=UITextFieldViewModeAlways;
    //右图片
    textField.rightView=rightImageView;
    //编辑状态下一直存在
    textField.rightViewMode=UITextFieldViewModeWhileEditing;
    //自定义键盘
    //textField.inputView
    //字体
    textField.font=[UIFont systemFontOfSize:font];
    //字体颜色
    textField.textColor=[UIColor blackColor];
    return textField ;
    
}
#pragma  mark 适配器方法
+(UITextField*)createTextFieldWithFrame:(CGRect)frame placeholder:(NSString*)placeholder passWord:(BOOL)YESorNO leftImageView:(UIImageView*)imageView rightImageView:(UIImageView*)rightImageView Font:(float)font backgRoundImageName:(NSString*)imageName
{
    UITextField*text= [self createTextFieldWithFrame:frame placeholder:placeholder passWord:YESorNO leftImageView:imageView rightImageView:rightImageView Font:font];
    text.background=[UIImage imageNamed:imageName];
    return  text;
}

+(UIScrollView*)createScrollViewWithFrame:(CGRect)frame andContentSize:(CGSize)size
{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:frame];
    
    scrollView.pagingEnabled = YES;
    scrollView.contentSize = size;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.scrollsToTop = NO;
    return scrollView ;
}
+(UIPageControl*)createPageControlWithFrame:(CGRect)frame numberOfPages:(int)numberOfPages currentPage:(int)currentPage
{
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:frame];
    pageControl.numberOfPages = numberOfPages;
    pageControl.currentPage = currentPage;
    return pageControl;
}
+(UISlider*)createSliderWithFrame:(CGRect)rect andThumbImageName:(NSString*)thumbImageName
{
    UISlider *slider = [[UISlider alloc]initWithFrame:rect];
    slider.minimumValue = 0;
    slider.maximumValue = 1;
    [slider setThumbImage:[UIImage imageNamed:thumbImageName] forState:UIControlStateNormal];
    slider.maximumTrackTintColor = [UIColor grayColor];
    slider.minimumTrackTintColor = [UIColor yellowColor];
    slider.continuous = YES;
    slider.enabled = YES;
    return slider ;
}

+ (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
          * 手机号码
          * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
          * 联通：130,131,132,152,155,156,185,186
          * 电信：133,1349,153,180,189
          */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
          10         * 中国移动：China Mobile
          11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
          12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
          15         * 中国联通：China Unicom
          16         * 130,131,132,152,155,156,185,186
          17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
          20         * 中国电信：China Telecom
          21         * 133,1349,153,180,189
          22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
          25         * 大陆地区固话及小灵通
          26         * 区号：010,020,021,022,023,024,025,027,028,029
          27         * 号码：七位或八位
          28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
//判断输入的邮箱格式是否正确
+(BOOL)checkEmail:(NSString*)email
{
    NSString *Regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *Test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [Test evaluateWithObject:email];
}
//判断输入的qq格式是否正确
+(BOOL)checkQQ:(NSString*)qq
{
    NSString *Regex = @"^[1-9](\\d){4,9}$";
    NSPredicate *Test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [Test evaluateWithObject:qq];
}
//判断输入的身份证号格式是否正确
+(BOOL)checkIdCard:(NSString*)ID
{
    NSString *Regex = @"(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";
    NSPredicate *Test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [Test evaluateWithObject:ID];
}

//网页版－－不需要客户端软件
//#import <TencentOpenAPI/QQApi.h>
//#import "WXApiObject.h"
//#import "YXApi.h"
//判断是否安装了qq，微信等
//+(NSArray *)checkAllInstalled
//{
//    NSMutableArray *titleArray = [NSMutableArray new];
//    
//    //1.先判微信
//    if ([WXApi isWXAppInstalled])
//    {
//        NSLog(@"wx已经安装");
//        [titleArray addObject:@"wx"];
//    }
//    else
//    {
//        NSLog(@"wx没有安装");
//    }
//    
//    //2.再判qq
//    if ([QQApi isQQInstalled])
//    {
//        NSLog(@"qq已经安装");
//        [titleArray addObject:@"qq"];
//    }
//    else
//    {
//        NSLog(@"qq没有安装");
//    }
//    
//    if ([YXApi isYXAppInstalled])
//    {
//        NSLog(@"yx已经安装");
//        [titleArray addObject:@"yx"];
//    }
//    else
//    {
//        NSLog(@"yx没有安装");
//    }
//    
//    
//    return titleArray;
//}
#pragma mark -********************
#pragma mark -ZCControl.h
#pragma mark -********************


+(NSString *)stringFromDateWithHourAndMinute:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    [dateFormatter setDateFormat:@"HH:mm"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
}

#pragma -mark 判断导航的高度
+(float)isIOS7{
    
    float height;
    if (IOS7) {
        height=64.0;
    }else{
        height=44;
    }
    
    return height;
}

+(NSString *)platformString{
    // Gets a string with the device model
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    NSDictionary* d = nil;
    if (d == nil)
    {
        d = @{
              @"iPhone1,1": @"iPhone 2G",
              @"iPhone1,2": @"iPhone 3G",
              @"iPhone2,1": @"iPhone 3GS",
              @"iPhone3,1": @"iPhone 4",
              @"iPhone3,2": @"iPhone 4",
              @"iPhone3,3": @"iPhone 4 (CDMA)",
              @"iPhone4,1": @"iPhone 4S",
              @"iPhone5,1": @"iPhone 5",
              @"iPhone5,2": @"iPhone 5 (GSM+CDMA)",
              
              @"iPod1,1": @"iPod Touch (1 Gen)",
              @"iPod2,1": @"iPod Touch (2 Gen)",
              @"iPod3,1": @"iPod Touch (3 Gen)",
              @"iPod4,1": @"iPod Touch (4 Gen)",
              @"iPod5,1": @"iPod Touch (5 Gen)",
              
              @"iPad1,1": @"iPad",
              @"iPad1,2": @"iPad 3G",
              @"iPad2,1": @"iPad 2 (WiFi)",
              @"iPad2,2": @"iPad 2",
              @"iPad2,3": @"iPad 2 (CDMA)",
              @"iPad2,4": @"iPad 2",
              @"iPad2,5": @"iPad Mini (WiFi)",
              @"iPad2,6": @"iPad Mini",
              @"iPad2,7": @"iPad Mini (GSM+CDMA)",
              @"iPad3,1": @"iPad 3 (WiFi)",
              @"iPad3,2": @"iPad 3 (GSM+CDMA)",
              @"iPad3,3": @"iPad 3",
              @"iPad3,4": @"iPad 4 (WiFi)",
              @"iPad3,5": @"iPad 4",
              @"iPad3,6": @"iPad 4 (GSM+CDMA)",
              
              @"i386": @"Simulator",
              @"x86_64": @"Simulator"
              };
    }
    NSString* ret = [d objectForKey: platform];
    
    if (ret == nil)
    {
        return platform;
    }
    return ret;
}

#pragma mark 内涵图需要的方法
+ (NSString *)stringDateWithTimeInterval:(NSString *)timeInterval
{
    NSTimeInterval seconds = [timeInterval integerValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    return [format stringFromDate:date];
}



// 返回一个整数字符串加1后的新字符串
+ (NSString *)addOneByIntegerString:(NSString *)integerString
{
    NSInteger integer = [integerString integerValue];
    return [NSString stringWithFormat:@"%zd",integer+1];
}

#pragma mark -********************
#pragma mark -CheckCamera.h
#pragma mark -********************
#pragma mark-检查相机，摄像头，闪光灯，以及支持的媒体数据类型。image movie 以及相册相关
-(void)checkCamera{
    if ([self iSAvailCamera]) {
        NSLog(@"摄像机可用");
    }else{
        NSLog(@"摄像机不可用");
    }
    
    if ([self iSAvailCameraFront]) {
        NSLog(@"摄像机前置摄像头可用");
    }else{
        NSLog(@"摄像机前置摄像头不可用");
    }
    if ([self iSAvailCameraRear]) {
        NSLog(@"摄像机后置摄像头可用");
    }else{
        NSLog(@"摄像机后置摄像头不可用");
    }
    if ([self iSAvailCameraFlashFront]) {
        NSLog(@"摄像机前置摄像头闪光灯可用");
    }else{
        NSLog(@"摄像机前置摄像头闪光灯不可用");
    }
    if ([self iSAvailCameraFlashRear]) {
        NSLog(@"摄像机后置摄像头闪光灯可用");
    }else{
        NSLog(@"摄像机后置摄像头闪光灯不可用");
    }
    
    
    //检查当前Camera支持的媒体类型：image video movie //kUTType不提示，但导入头文件后可用。
    if ([self doesCameraSupportTakingPhotos]) {
        NSLog(@"camera 支持拍照");
    }else{
        NSLog(@"camera 不支持拍照");
    }
    if ([self doesCameraSupportShootingVideos]) {
        NSLog(@"camera 支持录像");
    }else{
        NSLog(@"camera 不支持录像");
    }
    
    //检查相册是否可用
    if ([self isPhotoLibraryAvailable]) {
        NSLog(@"相册可用");
    } else {
        NSLog(@"相册不可用");
    }
    
    //是否可以在相册中选择照片
    if ([self canUserPickPhotosFromPhotoLibrary]) {
        NSLog(@"可以在相册中选择照片");
    } else {
        NSLog(@"不可以在相册中选择照片");
        
    }
    
    //是否可以在相册中选择视频
    if ([self canUserPickVideosFromPhotoLibrary]) {
        NSLog(@"可以在相册中选择视频");
    } else {
        NSLog(@"不可以在相册中选择视频");
    }
    
    
}

//检查摄像机是否可用
-(BOOL)iSAvailCamera{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
//检查前后摄像头是否可用
-(BOOL)iSAvailCameraFront{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}
-(BOOL)iSAvailCameraRear{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}
//检查前后闪光灯是否可用
-(BOOL)iSAvailCameraFlashFront{
    return [UIImagePickerController isFlashAvailableForCameraDevice:UIImagePickerControllerCameraDeviceFront];
}
-(BOOL)iSAvailCameraFlashRear{
    return [UIImagePickerController isFlashAvailableForCameraDevice:UIImagePickerControllerCameraDeviceRear];
}

//支持的媒体类型
-(BOOL)cameraSupportsMedia:(NSString *)paraMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceTyep{
    __block BOOL result = NO;
    if ([paraMediaType length] == 0) {
        NSLog(@"Media type is empty");
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceTyep];
    //public.image,public.movie
    [availableMediaTypes enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paraMediaType]) {
            result = YES;
            *stop = YES;
        }
    }];
    return result;
}
//检查摄像头是否支持拍照
-(BOOL) doesCameraSupportTakingPhotos{
    /*在此处注意我们要将MobileCoreServices 框架添加到项目中，
     然后将其导入：#import <MobileCoreServices/MobileCoreServices.h> 。不然后出现错误使用未声明的标识符 'kUTTypeImage'
     */
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

//检查摄像头是否支持录像
-(BOOL) doesCameraSupportShootingVideos{
    /*在此处注意我们要将MobileCoreServices 框架添加到项目中，
     然后将其导入：#import <MobileCoreServices/MobileCoreServices.h> 。不然后出现错误使用未声明的标识符 'kUTTypeMovie'
     */
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypeCamera];
}

#pragma mark- 相册相关
//相册是否可用
-(BOOL)isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
}
//是否可以在相册中选择照片
-(BOOL)canUserPickPhotosFromPhotoLibrary{
    return [self cameraSupportsMedia:(__bridge NSString*)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
//是否可以在相册中选择视频
-(BOOL)canUserPickVideosFromPhotoLibrary{
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

#pragma mark -********************
#pragma mark -ClearCacheTool.h
#pragma mark -********************
#pragma mark - 获取path路径下文件夹大小
+ (NSString *)getCacheSizeWithFilePath:(NSString *)path{
    
    /* subpathsAtPath: returns an NSArray of all contents and subpaths recursively from the provided path. This may be very expensive to compute for deep filesystem hierarchies, and should probably be avoided.
     */
    
    // 获取“path”文件夹下的所有文件 －－递归处理的
    NSArray *subPathArr = [[NSFileManager defaultManager] subpathsAtPath:path];
    
    NSString *filePath  = nil;
    NSInteger totleSize = 0;
    
    for (NSString *subPath in subPathArr){
        
        // 1. 拼接每一个文件的全路径
        filePath =[path stringByAppendingPathComponent:subPath];
        
        // 2. 是否是文件夹，默认不是
        BOOL isDirectory = NO;
        
        // 3. 判断文件是否存在
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
        
        
        // 4. 以上判断目的是忽略不需要计算的文件
        if (!isExist || isDirectory || [filePath containsString:@".DS"]){
            // 过滤: 1. 文件夹不存在  2. 过滤文件夹  3. 隐藏文件
            continue;
        }
        
        // 5. 指定路径，获取这个路径的属性
        NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        /**
         attributesOfItemAtPath: 文件夹路径
         该方法只能获取文件的属性, 无法获取文件夹属性, 所以也是需要遍历文件夹的每一个文件的原因
         */
        
        // 6. 获取每一个文件的大小
        NSInteger size = [dict[@"NSFileSize"] integerValue];
        
        // 7. 计算总大小
        totleSize += size;
    }
    
    //8. 将文件夹大小转换为 M/KB/B
    NSString *totleStr = nil;
    
    if (totleSize > 1000 * 1000){
        totleStr = [NSString stringWithFormat:@"%.2fM",totleSize / 1000.00f /1000.00f];
        
    }else if (totleSize > 1000){
        totleStr = [NSString stringWithFormat:@"%.2fKB",totleSize / 1000.00f ];
        
    }else{
        totleStr = [NSString stringWithFormat:@"%.2fB",totleSize / 1.00f];
    }
    
    return totleStr;
}


#pragma mark - 清除path文件夹下缓存大小
+ (BOOL)clearCacheWithFilePath:(NSString *)path{
    
    /* contentsOfDirectoryAtPath:error: returns an NSArray of NSStrings representing the filenames of the items in the directory. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. If the directory contains no items, this method will return the empty array.
     
     This method replaces directoryContentsAtPath:
     */
    //拿到path路径的下一级目录的子文件夹--没有使用递归
    NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    
    NSString *message  = nil;
    NSString *filePath = nil;
    
    NSError *error = nil;
    
    for (NSString *subPath in subPathArr)
    {
        filePath = [path stringByAppendingPathComponent:subPath];
        
        //删除子文件夹－－该方法可以删除该路径下的文件和文件夹（也即文件项）
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (error) {
            message = @"删除子文件夹失败";
            NSLog(@"message=%@",message);
            return NO;
        }
    }
    return YES;
}


#pragma mark - 获取具体文件的大小
+ (NSString *)getSizeWithData:(NSData *)data{
    
    NSInteger totleSize = 0;
    totleSize = data.length;
    
    //8. 将文件夹大小转换为 M/KB/B
    NSString *totleStr = nil;
    
    if (totleSize > 1000 * 1000){
        totleStr = [NSString stringWithFormat:@"%.2fM",totleSize / 1000.00f /1000.00f];
        
    }else if (totleSize > 1000){
        totleStr = [NSString stringWithFormat:@"%.2fKB",totleSize / 1000.00f ];
        
    }else{
        totleStr = [NSString stringWithFormat:@"%.2fB",totleSize / 1.00f];
    }
    
    NSLog(@"size = %@",totleStr);
    
    return totleStr;
}

#pragma mark -********************
#pragma mark -GetFilePath.h
#pragma mark -********************
//获取文件夹路径
+ (NSString *)getDocumentPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths objectAtIndex:0];
    
    //    //拼接一个sources文件夹－－该方法不开行啊－－对document文件夹在进行拼接文件夹会写入失败
    //    documentPath = [documentPath stringByAppendingPathComponent:@"sources"];
    
    return documentPath;
}

//获取指定文件路径
+ (NSString *)getSavePathWithFileSuffix:(NSString *)suffix
{
    
    NSString * documentPath = [self getDocumentPath];
    
    NSDate *date = [NSDate date];
    //获取当前时间
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMddHHmmss"];
    NSString *curretDateAndTime = [dateFormat stringFromDate:date];
    
    //    //获取用户userID
    //    NSDictionary *userDic= [[NSUserDefaults standardUserDefaults] objectForKey:UserInformation];
    
    NSString *sourceType = nil;
    if ([suffix isEqualToString:@"png"]) {
        sourceType = @"image";
    } else {
        sourceType = @"movie";
    }
    
    //命名文件
    NSString *fileName = [NSString stringWithFormat:@"%@%@.%@",sourceType,curretDateAndTime,suffix];
    //指定文件存储路径
    NSString *filePath = [documentPath stringByAppendingPathComponent:fileName];
    
    return filePath;
}



#pragma mark --获取图片的缩略图方法正确
//1.自动缩放到指定大小－－不保持宽高比
+(UIImage *)thumbnailWithImage:(UIImage *)image size:(CGSize)asize
{
    
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        UIGraphicsBeginImageContext(asize);
        [image drawInRect:CGRectMake(0, 0, asize.width, asize.height)];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}


#pragma mark --下面的两个方法 1.前一个方法的最终处理是对图片进行 填充 使达到目标大小  2.后一个方法的最终处理是对图片进行 裁剪 使达到目标大小

/**
 该方法的实现原理是：
 1. 用目标宽高比 与 原始图片宽高比进行比较--根据比较结果做处理
 2.如果目标宽高比大－－ 首先取目标的高为绘制时的高，然后通过目标的高 乘以 原始图片宽高比获取绘制时的宽 （目标宽高比较大－－说明原始图片宽高比较小－－从而计算出来的宽 比 目标的宽小－－进行正方向平移）
 3.如果目标宽高比小－－ 首先取目标的宽为绘制时的宽，然后通过目标的宽 乘以 原始图片高宽比获取绘制时的高  （目标宽高比较小也即目标的高宽比大－－说明原始图片高宽比较小－－从而计算出来的高 比 目标的高小－－进行正方向平移）
 4.根据1，2结果进行正方向平移处理
 5.这将导致绘制图片内容的尺寸比 目标大小 小－－（该方法的处理方式是：对不够的部分进行填充（底色））
 */
//2.保持原来的长宽比，生成一个缩略图
+(UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        
        CGSize oldsize = image.size;
        CGRect rect;
        //采取的方案是：保证一边的缩放正合适，另一边进行平移截取
        
        /**
         *  用目标宽高比 与 原始图片宽高比进行比较
         1.如果目标宽高比大－－ 首先取目标的高为绘制时的高，然后通过目标的高 乘以 原始图片宽高比获取绘制时的宽
         2.如果目标宽高比小－－ 首先取目标的宽为绘制时的宽，然后通过目标的宽 乘以 原始图片高宽比获取绘制时的高
         3.根据1，2结果（比目标尺寸小）进行正方向平移处理－－进行底色填充
         */
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*(oldsize.width/oldsize.height);
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*(oldsize.height/oldsize.width);
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
    
}


//该方法原理上是保持了宽高比处理的
//iOS图片生成小缩略图－－该方法采用的是放缩某一个方向到目标大小刚刚好，且取的是较大的放缩比例因子。则另一个方向的放缩比例(放大时会比目标值大，缩小时也比目标值大)，会导致比目标大小大，然后往负方向平移一段距离，使可见部分与目标大小刚好一致，截取中间目标大小部分。
/**
 该方法的实现原理是：
 1.将原始图片的大小 与目标大小进行比较，判断是否相等－－相等直接绘制即可
 2.(如果1中比较结果是不等，那么就要对图片进行放缩处理－－处理原则是保持宽高比)
 3.用目标图片的宽 高分别与原始图片的宽 高进行相除，获取缩放因子
 4.将宽和高的缩放因子进行比较 取较大者 [ 这样处理的结果将导致，取的缩放因子的方向将刚刚好缩放的目标值，而另一方向将导致放缩比例偏大（放大时会比目标值大，缩小时也比目标值大）,导致比目标值大]。
 5.截取比目标值大的方向－－的中间恰好是目标值大小的部分(具体处理如下：将该方向的图片的起始位置向负方向进行平移一段距离[（当前值－目标值）／ 2.0]) 一段距离就是 当前值减去目标值的一半，这样刚好取到该方向上的中间部分
 6.这将导致绘制图片内容的尺寸比 目标大小 大－－（该方法的处理方式是：对超过的部分进行裁剪（干掉））
 */
//3.iOS图片生成小缩略图－－该方法原理上是保持了宽高比处理的 获取指定大小的图片
+ (UIImage *)imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    
    UIImage *newImage = nil;
    
    //原始数据
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    //目标数据
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;//此处只是做默认的初始化--对下面的if判断为真时的赋值
    CGFloat scaledHeight = targetHeight;//此处只是做默认的初始化
    
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    //size即targetSize 与原始sourceImageSize不等
    if(CGSizeEqualToSize(imageSize, size) == NO)
    {
        //用目标宽高 除以 原始宽高 获得缩放比例因子
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        //取缩放因子中的较大值
        scaleFactor = widthFactor > heightFactor ? widthFactor : heightFactor;
        
        //无论是取的宽的缩放因子，还是高的缩放因子，取谁代表谁的比例缩放到目标大小刚刚好(因为两者相除得到比例因子，然后乘以比例因子就可以获得目标值)。 至于另一个方向缩放比例就肯定不可能是目标值（在这里指的是大），得另外处理，见下面。
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        //此处的另外处理－－（比目标尺寸大）就是进行了向负方向的平移（取中间的目标长度部分绘制）
        if(widthFactor > heightFactor){//无论是取的宽的缩放因子，还是高的缩放因子，取谁代表谁的比例缩放到目标大小刚刚好(而且这里是谁大就取谁)  那么必定导致另一个方向的拉伸变大，因为比例因子大了。
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    //设置scale的值
    UIGraphicsBeginImageContextWithOptions(size, NO, 1.0);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
        
    }
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}






#pragma mark --获取录像的缩略图方法正确

#pragma mark --下面两方法实现一样，只是参数不同而已
//获取录像的缩略图
+ (UIImage *)getVideoThumbnailWithUrl:(NSURL *)videoUrl{
    MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoUrl];
    moviePlayer.shouldAutoplay = NO;
    UIImage *image = [moviePlayer thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
    return image;
}

+ (UIImage *)getVideoThumbnailWithFilePath:(NSString *)filePath
{
    MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];
    moviePlayer.shouldAutoplay = NO;
    UIImage *image = [moviePlayer thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
    return image;
}


#pragma mark --下面两方法实现一样，只是参数不同而已
//获取录像缩略图byVideoUrl
+ (UIImage *)getImageByVideo:(NSURL *)videoUrl{
    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    
    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:videoUrl options:options];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(60, 60);
    
    //获得CGImageRef为nil
    NSError *error = nil;
    CGImageRef imageRef = [generator copyCGImageAtTime:CMTimeMake(10, 10) actualTime:NULL error:&error];
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    return image;
    
}

/**
 Error Domain=AVFoundationErrorDomain Code=-11828 "Cannot Open" UserInfo={NSLocalizedDescription=Cannot Open, NSUnderlyingError=0x155e63f0 {Error Domain=NSOSStatusErrorDomain Code=-12847 "(null)"}, NSLocalizedFailureReason=This media format is not supported.
 */
//获取录像的缩略图(该方法对图片似乎不管用，报数据类型不正确，说明它们都是获取录像缩略图的方法)
+ (UIImage *)getImage:(NSString *)filePath
{
    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    
    NSURL *url = [NSURL fileURLWithPath:filePath];
    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:url options:options];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(60, 60);
    
    //获得CGImageRef为nil
    NSError *error = nil;
    CGImageRef imageRef = [generator copyCGImageAtTime:CMTimeMake(10, 10) actualTime:NULL error:&error];
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    return image;
}


/**
 在处理图片中由于服务端等等原因我们需要对图片做一个规格处理、比如图片的体积。图片的质量。如果我们只是处理质量而不处理体积这样图片可能即使很大也很模糊等等。。。该内容对图片的压缩采用图片系数压缩。并不是指定的长度宽度压缩。
 
 在现实中需要质量压缩和体积压缩共同使用才能达到效果：
 */


//在现实中需要质量压缩和体积压缩共同使用才能达到效果：
+(UIImage *)imageUserToCompressForSizeImage:(UIImage *)image newSize:(CGSize)size{
    
    UIImage *newImage = nil;
    
    CGSize originalSize = image.size;//获取原始图片size
    CGFloat originalWidth = originalSize.width;//
    CGFloat originalHeight = originalSize.height;//高
    
    if ((originalWidth <= size.width) && (originalHeight <= size.height)) {
        newImage = image;//宽和高同时小于要压缩的尺寸时返回原尺寸
    }
    else{
        
        //新图片的宽和高
        CGFloat scale = (float)size.width/originalWidth < (float)size.height/originalHeight ? (float)size.width/originalWidth : (float)size.height/originalHeight;
        CGSize newImageSize = CGSizeMake(originalWidth*scale , originalHeight*scale );
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(newImageSize.width , newImageSize.height ), NO, 0);
        [image drawInRect:CGRectMake(0, 0, newImageSize.width, newImageSize.height) blendMode:kCGBlendModeNormal alpha:1.0];
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        if (newImage == nil) {
            NSLog(@"image ");
        }
        UIGraphicsEndImageContext();
        
    }
    return newImage;
}

#pragma mark -********************
#pragma mark -ViewHierarchyLogging.h
#pragma mark -********************
//-(void)logViewHierarchy{
//    //NSLog(@"%@",self);
//    for (UIView *subView in self.subviews) {
//        
//        
//        
//        NSString *className = NSStringFromClass(subView.class);
//        NSLog(@"%@",className);
//        
//        if ([className isEqualToString:@"PLImagePickerCameraView"]) {
//            CGRect frame = subView.frame;
//            CGRect newFrame = CGRectMake(0,0,frame.size.width,frame.size.height);
//            subView.frame = newFrame;
//        }
//        
//        [subView logViewHierarchy];
//    }
//}
//
//
//-(void)logViewHierarchy1{
//    NSLog(@"%@",self);
//    for (UIView *subView in self.subviews) {
//        
//        //        NSString *className = NSStringFromClass(subView.class);
//        //        NSLog(@"%@",className);
//        //
//        //        if ([className isEqualToString:@"CMKPreviewView"]) {
//        //            CGRect frame = subView.frame;
//        //            CGRect newFrame = CGRectMake(100, 100, frame.size.width, frame.size.height);
//        //            subView.frame = newFrame;
//        //        }
//        
//        [subView logViewHierarchy1];
//    }
//}


#pragma mark -********************
#pragma mark -ConstmBt.h  自定义 按钮点击 响应范围
#pragma mark -********************
//-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
//    if ([super pointInside:point withEvent:event]) {
//        
//        CGFloat radius = self.bounds.size.width;
//        CGFloat dx = point.x - self.bounds.size.width/2.0;
//        CGFloat dy = point.y - radius;
//        CGFloat distance = sqrt(dx * dx + dy * dy);
//        
//        //        NSLog(@"%f",distance);
//        //        NSLog(@"%f",radius);
//        return distance < radius;
//    }
//    
//    return NO;
//}


#pragma mark -********************
#pragma mark -TImeChange.h
#pragma mark -********************
/******** 2016-01-07T10:00:00.000Z 对于这种时间格式的时间转换 T（可为任意字符）.000Z(可不要)   **********/
-(NSString*)timeChange:(NSString*)timeStr
{
    
    NSString* dayStr = [timeStr substringToIndex:10];
    NSString* secondString = [timeStr substringWithRange:NSMakeRange(11, 8)];
    NSString* beforTime = [NSString stringWithFormat:@"%@ %@",dayStr,secondString];
    NSLog(@"%@",beforTime);
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
    
    NSDate *date1 = [formatter dateFromString:beforTime];
    NSLog(@"%@",date1);
    
    
    
    NSDate* date2 = [[NSDate alloc]initWithTimeInterval:8*60*60 sinceDate:date1];
    NSString * nowTime = [formatter stringFromDate:date2];
    NSLog(@"nowTime -- %@",nowTime);
    
    
    //时间更改
    NSDateFormatter* formatter1 = [[NSDateFormatter alloc]init];
    [formatter1 setDateFormat:@"YYYY-MM-DD HH:mm:ss"];
    NSString* data = [formatter1 stringFromDate:[NSDate date]];
    
    NSLog(@"%@",data);
    
    // 比较当前时间和给取的时间的差距
    NSInteger indexOfDisequal =  [self compareStr:data andStr2:nowTime];
    
    if (indexOfDisequal == 1 || indexOfDisequal == 2 || indexOfDisequal == 3 || indexOfDisequal == 4 || indexOfDisequal == 6 || indexOfDisequal == 7 || indexOfDisequal == 9 || indexOfDisequal == 10) {
        return nowTime;
    }
    else if (indexOfDisequal == 5 || indexOfDisequal ==8 || indexOfDisequal == 11 || indexOfDisequal == 14 || indexOfDisequal == 17)
    {
        return @"时间格式错误";
    }
    //小时
    else if (indexOfDisequal == 12 || indexOfDisequal == 13)
    {
        NSString* subStrH1 = [nowTime substringWithRange:NSMakeRange(11, 2)];
        NSString* subStrH2 = [data substringWithRange:NSMakeRange(11, 2)];
        
        
        
        if ([subStrH2 intValue]-[subStrH1 intValue] == 1) {
            
            //小时差在一个小时之间  要判断 是否超过一个小时
            NSString* subStr1 = [nowTime substringWithRange:NSMakeRange(14, 2)];
            NSString* subStr2 = [data substringWithRange:NSMakeRange(14, 2)];
            if ([subStr2 intValue]-[subStr1 intValue] >=0) {
                return [NSString stringWithFormat:@"%d小时前", [subStrH2 intValue]-[subStrH1 intValue]];
            }else
            {
                return [NSString stringWithFormat:@"%d分钟前", 60+[subStr2 intValue]-[subStr1 intValue]];
            }
            
        }else
        {
            NSString* subStr1 = [nowTime substringWithRange:NSMakeRange(14, 2)];
            NSString* subStr2 = [data substringWithRange:NSMakeRange(14, 2)];
            if ([subStr2 intValue]-[subStr1 intValue]>0) {
                return [NSString stringWithFormat:@"%d小时前", [subStrH2 intValue]-[subStrH1 intValue]];
            }else
            {
                return [NSString stringWithFormat:@"%d小时前", [subStrH2 intValue]-[subStrH1 intValue]-1];
            }
            
        }
        
        
    }
    // 分钟
    else if (indexOfDisequal == 15 || indexOfDisequal == 16)
    {
        NSString* subStr1 = [nowTime substringWithRange:NSMakeRange(14, 2)];
        NSString* subStr2 = [data substringWithRange:NSMakeRange(14, 2)];
        return [NSString stringWithFormat:@"%d分钟前", [subStr2 intValue]-[subStr1 intValue]];
    }
    else
    {
        return @"1分钟以前";
    }
    
}

//第几个数不相同 0表示全部相同
-(NSInteger)compareStr:(NSString* )str1 andStr2:(NSString*)str2
{
    //你的时间格式必须为YYYY-MM-DD-hh:mm:ss
    for (NSInteger i = 0; i<str1.length; i++) {
        NSString* subStr1 = [str1 substringWithRange:NSMakeRange(i, 1)];
        NSString* subStr2 = [str2 substringWithRange:NSMakeRange(i, 1)];
        if ([subStr1 isEqualToString:subStr2]) {
        }else
            return i+1;
    }
    
    return 0;
}

//1表示闰年，0表示非闰年
+(NSInteger)isRunYear:(NSInteger)year
{
    if (!(year%100)) {
        return 0;
    }
    else{
        
        if (!(year%4)) {
            return 1;
        }
        else{
            return 0;
            
        }
    }
}

//获得1970年至今的毫秒数
+(NSInteger)getTimeFrom1970
{
    NSTimeInterval time=[[NSDate date] timeIntervalSince1970]*1000;
    NSInteger i=time;      //NSTimeInterval返回的是double类型
    
    return i;
    
}
//获得当前时间
+(NSString*)getNowTime
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSString* dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

//获得当前时间
+(NSString*)getNowTimewithStyle:(NSString*)style
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:style];
    NSString* dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

//将秒数转成分钟与小时(不足一分钟按一分钟算，不足一小时按一小时算)
+(NSString*)getSecondTominutesOrHoour:(NSInteger)time
{
    if (time/60) {
        if (time/3600) {
            return [NSString stringWithFormat:@"使用时长：%ld小时",(long)time/3600+1];
        }
        else
        {
            return [NSString stringWithFormat: @"使用时长：%ld分钟",(long)time/60 +1 ];
        }
    }
    else
    {
        return @"使用时长：1分钟";
    }
}

// 后台时间专成当前年月
+(NSString*)javaSecondToHourWithStyle:(NSString*)style andJavaTime:(long)time
{
    NSDate* tempDate = [NSDate dateWithTimeIntervalSince1970:(time / 1000)];
    NSDateFormatter* dateFoemate = [[NSDateFormatter alloc]init];
    [dateFoemate setDateFormat:style];
    NSString* str1 = [dateFoemate stringFromDate:tempDate];
    return str1;
}

// 后台时间专程转成周几（一周以内星期几，一天以内几点几分，今天显示）
+(NSString*)javaTimeToWeekOrDayOrHourWithTime:(long)time
{
    
    
    NSArray* weekday = @[@"星期天",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
    NSDate* newDate = [NSDate dateWithTimeIntervalSince1970:time/1000];
    
    NSDateFormatter* dateFoemate1 = [[NSDateFormatter alloc]init];
    [dateFoemate1 setDateFormat:@"yyyy-MM-dd"];
    NSString* strjjj = [dateFoemate1 stringFromDate:newDate];
    NSLog(@"%@",strjjj);
    
    // 坑死爸爸了，这货从1开始
    NSCalendar* calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [calendar components:NSCalendarUnitWeekday fromDate:newDate];
    NSInteger i = components.weekday;
    NSLog(@"%zd",i);
    NSString* weekStr = [weekday objectAtIndex:(components.weekday-1)];
    
    //获得当前时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy/MM/dd"];
    NSString* dateTime = [formatter stringFromDate:[NSDate date]];
    
    //获得传过来的时间的天数
    NSDate* tempDate = [NSDate dateWithTimeIntervalSince1970:(time / 1000)];
    NSDateFormatter* dateFoemate = [[NSDateFormatter alloc]init];
    [dateFoemate setDateFormat:@"yyyy/MM/dd"];
    NSString* str1 = [dateFoemate stringFromDate:tempDate];
    
    //当天
    if ([str1 isEqualToString:dateTime]) {
        NSDate* tempDate = [NSDate dateWithTimeIntervalSince1970:(time / 1000)];
        NSDateFormatter* dateFoemate = [[NSDateFormatter alloc]init];
        [dateFoemate setDateFormat:@"HH:mm"]; // 大写24小时制
        NSString* str1 = [dateFoemate stringFromDate:tempDate];
        return str1;
    }
    //昨天
    else
    {
        NSTimeInterval timenow =[[NSDate date] timeIntervalSince1970]*1000;
        // NSDate* newDate = [NSDate dateWithTimeIntervalSinceNow:timenow];
        
        NSDate* tempDate = [NSDate dateWithTimeIntervalSince1970:(timenow / 1000)];
        NSDateFormatter* dateFoemate = [[NSDateFormatter alloc]init];
        [dateFoemate setDateFormat:@"HHmm"]; // 大写24小时制
        NSString* str1 = [dateFoemate stringFromDate:tempDate];
        long haoMiao = 1000*3600*24;
        for (int i= 0 ; i<4; i++) {
            NSString* tempStr = [str1 substringWithRange:NSMakeRange(i, 1)];
            if (i==0) {
                
                haoMiao += ([tempStr intValue] * 1000*3600*10);
                
            }
            if (i==1) {
                
                haoMiao += ([tempStr intValue] * 1000*3600);
            }
            if (i==2) {
                haoMiao += ([tempStr intValue] * 1000*60);
            }
            if (i==3) {
                haoMiao += ([tempStr intValue] * 1000);
            }
        }
        
        if ((haoMiao + time)>timenow ) {
            return @"昨天";
        }
        // 一周以内
        else
        {
            if ((haoMiao+time+3600*1000*24*6)>timenow) {
                return weekStr;
            }
            else
            {
                NSDate* tempDate = [NSDate dateWithTimeIntervalSince1970:(time / 1000)];
                NSDateFormatter* dateFoemate = [[NSDateFormatter alloc]init];
                [dateFoemate setDateFormat:@"yyyy－MM－dd"];
                NSString* str1 = [dateFoemate stringFromDate:tempDate];
                return str1;
            }
        }
        
    }
    
}

//根据毫秒来的到几岁 返还虚岁 一岁半算1岁
+(NSString*)getAgeWithTime:(long)time
{
    NSDate* tempDate = [NSDate dateWithTimeIntervalSince1970:(time / 1000)];
    NSDateFormatter* dateFoemate = [[NSDateFormatter alloc]init];
    [dateFoemate setDateFormat:@"yyyyMMdd"];
    NSString* strBirth = [dateFoemate stringFromDate:tempDate];
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString* dateTime = [formatter stringFromDate:[NSDate date]];
    
    NSString* strYear1 = [strBirth substringWithRange:NSMakeRange(0, 4)];
    NSString* strYear2 = [dateTime substringWithRange:NSMakeRange(0, 4)];
    
    NSInteger year = [strYear2 integerValue] - [strYear1 integerValue];
    
    NSString* strMonth = [strBirth substringWithRange:NSMakeRange(4, 2)];
    NSString* strMonth1 = [strBirth substringWithRange:NSMakeRange(4, 2)];
    
    if ([strMonth integerValue] <[strMonth1 integerValue]) {  //
        
        return [NSString stringWithFormat:@"%zd",year];
    }
    else if ([strMonth integerValue] <[strMonth1 integerValue])
    {
        return [NSString stringWithFormat:@"%zd",year-1];
    }
    else
    {
        NSString* strDay = [strBirth substringWithRange:NSMakeRange(6, 2)];
        NSString* strDay1 = [strBirth substringWithRange:NSMakeRange(6, 2)];
        if (strDay<strDay1) {
            return [NSString stringWithFormat:@"%zd",year-1];
        }else
        {
            return [NSString stringWithFormat:@"%zd",year];
        }
    }
    
}

//根据年月日专成毫秒数
+(NSInteger)getTimeToSeconds:(NSString*)time andStyle:(NSString*)style
{
    
    
    NSDateFormatter* dateFormater = [[NSDateFormatter alloc]init];
    [dateFormater setDateFormat:style];
    NSDate* date = [dateFormater dateFromString:time];
    
    
    
    NSTimeInterval interval = [date timeIntervalSince1970];
    return (NSInteger)(interval*1000);
}
// 获得当前哪一年
+(NSString*)getnowYear
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSString* dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

#pragma mark -********************
/**********对文件进行操作************/
#pragma mark -"WWFileOperation.h"
#pragma mark -********************
// 创建文件件
+(BOOL)creatfolderWithName:(NSString*)name
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *createPath = [NSString stringWithFormat:@"%@/%@", pathDocuments,name];
    
    
    // 判断文件夹是否存在，如果不存在，则创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        return [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    } else {
        NSLog(@"FileDir is exists.");
    }
    return YES;
}

// 删除文件
+(BOOL)deleteFolderWithName:(NSString*)floder andSuffix:(NSString*)suffix;
{
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *createPath;
    if (floder == nil) {
        createPath = [NSString stringWithFormat:@"%@/%@", pathDocuments,suffix];
    }
    else
    {
        createPath = [NSString stringWithFormat:@"%@/%@/%@", pathDocuments,floder,suffix];
    }
    
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager removeItemAtPath:createPath error:nil];
    
}

// 写文件
+(BOOL)writeFileWithDocunemtName:(NSString*)name andFileSuffix:(NSString* ) suffixName andDataFile:(NSData*)data
{
    
    
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *createPath;
    
    if (name == nil) {
        createPath = [NSString stringWithFormat:@"%@/%@", pathDocuments,suffixName];
    }
    else
    {
        createPath = [NSString stringWithFormat:@"%@/%@/%@", pathDocuments,name,suffixName];
    }
    
    bool isBool = [data writeToFile:createPath atomically:YES];
    
    return isBool;
    
    
}
// 读文件
+(NSData*)readDataWithDocumentName:(NSString*)name andFileSuffix:(NSString*) suffixName
{
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *createPath;
    
    if (name == nil) {
        createPath = [NSString stringWithFormat:@"%@/%@", pathDocuments,suffixName];
    }
    else
    {
        createPath = [NSString stringWithFormat:@"%@/%@/%@", pathDocuments,name,suffixName];
    }
    
    
    NSData* data = [NSData dataWithContentsOfFile:createPath];
    return data;
    
}

@end
